<script setup>
import { onMounted, ref, watch } from "vue";
import { rewritePath } from "@/config/index.js";
import addressData from "@/utils/address.json";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const props = defineProps({
  info: {
    type: Object,
    default: () => {},
  },
});

watch(
  () => props.info,
  (newVal) => {
    if (props.info.avatar) formData.value.avatar = props.info.avatar;
    if (props.info.nickName) formData.value.nickName = props.info.nickName;
    if (props.info.address)
      formData.value.address = props.info.address.split(",");
    if (props.info.addressDetails)
      formData.value.addressDetails = props.info.addressDetails;
  }
);

const router = useRouter();
const actionUrl = rewritePath + "/system/user/profile/avatar";
const uploadHeaders = {
  Authorization: "Bearer " + localStorage.getItem("tokenSeller"),
};

const formData = ref({
  avatar: "",
  nickName: "",
  address: "",
});
const avatarUploading = ref(false);
const handleAvatarSuccess = (res, file) => {
  if (res.code === 200 && res.imgUrl) {
    formData.value.avatar = res.imgUrl;
  } else {
    ElMessage.error(res.msg);
    if (res.code === 401) {
      router.push("/login");
    }
  }
  avatarUploading.value = false;
};
const onProgress = () => {
  avatarUploading.value = true;
};

const rules = {
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 4, max: 12, message: "长度在 4 到 12 个字符", trigger: "blur" },
    { pattern: /^[^\s]{4,12}$/, message: "昵称不能包含空格", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "昵称只能包含数字、字母和下划线",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请选择常住地", trigger: "change" }],
  addressDetails: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
  avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
};

const ruleFormRef = ref();
const checkForm = async () => {
  try {
    await ruleFormRef.value.validate();
    return Promise.resolve();
  } catch (e) {
    return Promise.reject();
  }
};

defineExpose({
  formData: formData.value,
  checkForm,
});
</script>

<template>
  <div class="main-info">
    <h4 class="title"><span></span> 个人信息</h4>
    <div class="form">
      <el-form
        ref="ruleFormRef"
        :model="formData"
        label-position="top"
        :rules="rules"
      >
        <el-form-item required prop="avatar">
          <template #label>
            <p class="label">
              头像 <span>请上传真实得体的头像 （照片大小不超过10MB）</span>
            </p>
          </template>
          <el-upload
            v-loading="avatarUploading"
            background="rgba(0,0,0,.2)"
            class="avatar-uploader"
            :action="actionUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            name="avatarfile"
            :on-progress="onProgress"
            :on-success="handleAvatarSuccess"
            accept="image/png,image/jpeg,image/jpg"
          >
            
            <div
              class="upload-tips"
              :class="{ 'change-active': formData.avatar }"
            >
              <img v-if="formData.avatar" :src="formData.avatar" class="avatar"/>
              <img
                v-else
                v-if="!formData.avatar"
                src="@/assets/file-upload-icon.png"
                alt=""
              />
              <div class="upload-tips-content" v-if="formData.avatar">
                <img
                  src="@/assets/file-upload-icon-white.png"
                  alt=""
                />
                <p>{{ formData.avatar ? "替换头像" : "上传头像" }}</p>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" required prop="nickName">
          <el-input
            v-model="formData.nickName"
            placeholder="4-12字符，不支持特殊字符（间隔_除外）"
          ></el-input>
        </el-form-item>
        <el-form-item label="常住地" required prop="address">
          <el-cascader
            v-model="formData.address"
            style="width: 100%"
            :options="addressData"
            placeholder="选择地址"
            :props="{ value: 'name', label: 'name', children: 'city' }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item
          v-if="formData.address"
          label=""
          required
          prop="addressDetails"
        >
          <el-input
            v-model="formData.addressDetails"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main-info {
  width: 1200px;
  margin: 32px auto 20px;
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px;
  box-sizing: border-box;
  .title {
    display: flex;
    align-items: center;
    font-size: 16px;
    margin-bottom: 20px;
    span {
      width: 2px;
      height: 12px;
      background: #1dbf73;
      border-radius: 10px 10px 10px 10px;
      margin-right: 6px;
    }
  }
}
.avatar-uploader {
  width: 88px;
  height: 88px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.form {
  width: 650px;
}
.label {
  span {
    font-size: 12px;
    color: rgba(25, 30, 40, 0.36);
    margin-left: 8px;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader .upload-tips {
  font-size: 28px;
  color: #8c939d;
  width: 88px;
  height: 88px;
  text-align: center;
  border-radius: 44px 44px 44px 44px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 2;
  &.change-active {
    P {
      color: #fff;
    }
  }
  img {
    width: 24px;
    height: 24px;
  }
  p {
    color: rgba(25, 30, 40, 0.24);
    font-size: 12px;
  }

  .avatar {
    width: 88px;
    height: 88px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
    border-radius: 44px;
    
  }
  &:hover{
     .upload-tips-content{
        display: flex;
      }
    }
  .upload-tips-content{
      background: rgba(25, 30, 40, 0.34);
      width: 84px;
      height: 84px;
      border-radius: 50%;
      align-items: center;
      justify-content: center;
      display:none;
      flex-direction: column;
      align-items: center;
      position: relative;
      z-index: 1;
    }
}

</style>

<style>
.el-form-item--label-top .el-form-item__label p {
  display: inline;
}
</style>